package com.qdlc.p2p.biz.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.BorrowAutoService;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.BorrowAutoDao;
import com.qdlc.p2p.dal.dto.Borrow;
import com.qdlc.p2p.dal.dto.BorrowAuto;
import com.qdlc.p2p.dal.dto.User;

@Service("borrowAutoService")
public class BorrowAutoServiceImpl implements BorrowAutoService {

    @Resource
    private BorrowAutoDao borrowAutoDao;

    @Override
    public BorrowAuto init(User user) {
        BorrowAuto auto = borrowAutoDao.findObjByProperty("user.userId", user.getUserId());
        if (auto == null) {
            auto = new BorrowAuto(user);
            auto.setAddTime(DateUtil.getNow());
            auto.setAddIp(Global.getIP());
            borrowAutoDao.save(auto);
        }
        return auto;
    }

    @Override
    public void update(BorrowAuto auto) throws Exception {
        borrowAutoDao.update(auto);
    }

    @Override
    public int count(Borrow borrow) {
        return borrowAutoDao.count();
    }

    @Override
    public void modifyTime(BorrowAuto auto) {
        auto = borrowAutoDao.find(auto.getId());
        auto.setUpdateTime(DateUtil.getNow());
        borrowAutoDao.update(auto);
    }

    @Override
    public void add(BorrowAuto auto) {
        borrowAutoDao.save(auto);
    }

    @Override
    public BorrowAuto findByUser(User user) {
        QueryParam param = QueryParam.getInstance();
        param.addParam("user", user);
        return borrowAutoDao.findByCriteriaForUnique(param);
    }
}
